package com.ledim.activity.base;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.ledim.fragment.base.LeDimBaseFragment;
import com.ledim.utils.SystemBarTintManager;
import com.letv.android.client.fragment.LetvFragmentListener;
import com.letv.android.young.client.R;
import java.lang.reflect.Field;
import org.greenrobot.eventbus.EventBus;

/**
 * Created by ccx on 16/05/18.
 * Activity基类
 */
public abstract class LeDimBaseActivity extends FragmentActivity implements View.OnClickListener {

    /**
     * 传递参数
     */
    public Bundle intentData;
    /**
     * 参数传递标示
     */
    public static final String PARAM_INTENT = "intentData";
    public SystemBarTintManager tintManager;

    protected void addFragment(LeDimBaseFragment fragment, int fragmentId) {
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction()
                                       .replace(fragmentId, fragment)
                                       .addToBackStack(fragment.getClass().getSimpleName())
                                       .commitAllowingStateLoss();
        }
    }

    /**
     * 批量添加fragment
     *
     * @param fragments
     */
    public void addFragments(Fragment... fragments) {
        if (fragments == null || fragments.length == 0) {
            return;
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        for (Fragment fragment : fragments) {
            if (!(fragment instanceof LetvFragmentListener)) {
                continue;
            }

            LetvFragmentListener listener = (LetvFragmentListener) fragment;

            String tag = listener.getTagName();
            if (TextUtils.isEmpty(tag)) {
                continue;
            }

            int fragmentRes = listener.getContainerId();
            if (fragmentRes <= 0) {
                continue;
            }

            if (fragmentManager.findFragmentByTag(tag) != null) {
                continue;
            }

            transaction.add(fragmentRes, fragment, tag);
        }

        try {
            // catch Activity has been destroyed error
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected abstract int getContentLayoutId();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            intentData = getIntent().getExtras();
        } else {
            intentData = savedInstanceState.getBundle(PARAM_INTENT);
        }
        Bundle bundle = intentData != null && intentData.getBundle(PARAM_INTENT) != null
                        ? intentData.getBundle(PARAM_INTENT) : intentData;
        initIntentData(bundle != null ? bundle : new Bundle());
        setContentView(getContentLayoutId());
        tintManager = new SystemBarTintManager(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.statusbar);
        }
    }

    /**
     * 初始化页面传递过来的数据
     *
     * @param bundle
     *         数据
     */
    protected void initIntentData(Bundle bundle) {

    }

    @Override
    protected void onDestroy() {
        fixInputMethodManagerLeak(this);
        super.onDestroy();
    }

    public void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm =
                (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[] { "mCurRootView", "mServedView", "mNextServedView" };
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                }
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() ==
                            destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
                        //if (QLog.isColorLevel()) {
                        //    QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
                        //}
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    protected <T extends View> T findViewByIdExt(int resId) {
        return (T) findViewById(resId);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * @return 是否使用EventBus 默认不使用
     */
    protected boolean useEventBus() {
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        // overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public void finish() {
        super.finish();
        //overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public void onClick(View v) {

    }

    public void goToOthers(Class<?> cls) {
        goToOthers(cls, null);
    }

    public void goToOthersF(Class<?> cls) {
        goToOthers(cls);
        finish();
    }

    public void goToOthers(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(LeDimBaseActivity.PARAM_INTENT, bundle);
        startActivity(intent);
    }

    public void goToOthersF(Class<?> cls, Bundle bundle) {
        goToOthers(cls, bundle);
        finish();
    }

    public void upToHome(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(LeDimBaseActivity.PARAM_INTENT, bundle);
        startActivity(intent);
        finish();
    }

    public void upToHome(Class<?> cls) {
        upToHome(cls, null);
    }

    public void homeAction() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// ע��
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    public void goToOthersForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(LeDimBaseActivity.PARAM_INTENT, bundle);
        startActivityForResult(intent, requestCode);
    }

    public void backForResult(Class<?> cls, Bundle bundle, int resultCode) {
        Intent intent = new Intent();
        if (cls != null) {
            intent.setClass(this, cls);
        }
        intent.putExtra(LeDimBaseActivity.PARAM_INTENT, bundle);
        setResult(resultCode, intent);
        finish();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Bundle bundle = null;
        if (data != null) {
            bundle = data.getBundleExtra(PARAM_INTENT);
            if (bundle == null) {
                bundle = data.getExtras();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
        onActivityResult(requestCode, resultCode, bundle);
    }

    /**
     * 页面回调函数
     *
     * @param requestCode
     *         请求码
     * @param resultCode
     *         返回码
     * @param data
     *         数据
     */
    protected void onActivityResult(int requestCode, int resultCode, Bundle data) {

    }
}
